<template>
  <q-btn-group class="absolute map-operation-bar bg-grey-7">
    <q-btn :color="activeCls('move')" :label="$t('MapCore.Roaming')" icon="pan_tool" v-bind="btnAttrs"
      @click="setCurrentAction('move')"></q-btn>
    <q-btn :color="activeCls('line')" :label="$t('MapCore.Gline')" icon="mdi-vector-line" v-bind="btnAttrs"
      @click="setCurrentAction('line')"></q-btn>
    <q-btn :color="activeCls('curve')" :label="$t('MapCore.Curve')" icon="mdi-vector-curve" v-bind="btnAttrs"
      @click="setCurrentAction('curve')">
      <q-popup-proxy v-bind="popupAttrs" v-bind:offset="[3, 3]" @before-hide="curvePopupHide">
        <qx-form v-model="curveForm" :option="curveOption" class="q-pa-md curve-form-cls" nonTop></qx-form>
      </q-popup-proxy>
    </q-btn>
    <q-btn :color="activeCls('area')" :label="$t('MapCore.Area')" icon="mdi-select" v-bind="btnAttrs"
      @click="setCurrentAction('area')"></q-btn>
    <q-btn :color="activeCls('text')" :label="$t('MapCore.Text')" icon="text_fields" v-bind="btnAttrs"
      @click="setCurrentAction('text')"></q-btn>
    <q-btn :color="activeCls('pointSelection')" :label="$t('MapCore.BatchPointSelection')" icon="mdi-select-marker"
      v-bind="btnAttrs" @click="setCurrentAction('pointSelection')"></q-btn>
    <q-btn :label="$t('MapCore.BatchLine')" icon="mdi-vector-polyline-edit" v-bind="btnAttrs">
      <q-popup-proxy v-bind="popupAttrs" @hide="batchLineHide" @before-show="batchLineBeforeShow">
        <q-list class="bg-grey-7 text-white q-pa-sm">
          <q-item v-for="column in batchLineColumns" :key="column.field" @click="handleBatchLine('bothway')">
            <q-checkbox v-model="batchLineForm[column.field]" :disable="column.disable || batchLineForm[column.field]"
              :label="column.label" dark dense @update:modelValue="handleBatchLine(column.field)"></q-checkbox>
          </q-item>
        </q-list>
      </q-popup-proxy>
    </q-btn>
    <q-btn :color="activeCls('lineSelection')" :label="$t('MapCore.BatchLintSelection')" icon="mdi-selection-drag"
      v-bind="btnAttrs" @click="setCurrentAction('lineSelection')"></q-btn>
    <q-btn :label="$t('Misc.Align')" icon="mdi-align-horizontal-left" v-bind="btnAttrs">
      <q-icon class="drop-down-badge" name="arrow_right"></q-icon>
      <q-popup-proxy v-bind="popupAttrs">
        <q-list class="bg-grey-7 text-white text-caption" dense>
          <q-item v-close-popup class="row no-wrap items-center" clickable @click="handleXY('align', 'lX')">
            <q-icon class="q-pr-xs" name="mdi-align-horizontal-left"></q-icon>
            <div>{{ $t('Misc.LeftJustifying') }}</div>
          </q-item>
          <q-item v-close-popup class="row no-wrap items-center" clickable @click="handleXY('align', 'rX')">
            <q-icon class="q-pr-xs" name="mdi-align-horizontal-right"></q-icon>
            <div>{{ $t('Misc.FlushRight') }}</div>
          </q-item>
          <q-item v-close-popup class="row no-wrap items-center" clickable @click="handleXY('align', 'tY')">
            <q-icon class="q-pr-xs" name="mdi-align-vertical-top"></q-icon>
            <div>{{ $t('Misc.AlignTop') }}</div>
          </q-item>
          <q-item v-close-popup class="row no-wrap items-center" clickable @click="handleXY('align', 'bY')">
            <q-icon class="q-pr-xs" name="mdi-align-vertical-bottom"></q-icon>
            <div>{{ $t('Misc.BottomAlign') }}</div>
          </q-item>
        </q-list>
      </q-popup-proxy>
    </q-btn>
    <q-btn :icon="biDistributeHorizontal" :label="$t('Misc.Distribution')" v-bind="btnAttrs">
      <q-icon class="drop-down-badge" name="arrow_right"></q-icon>
      <q-popup-proxy v-bind="popupAttrs">
        <q-list class="bg-grey-7 text-white text-caption" dense>
          <q-item v-close-popup class="row no-wrap items-center" clickable @click="handleXY('distribution', 'x')">
            <q-icon :name="biDistributeHorizontal" class="q-pr-xs"></q-icon>
            <div>{{ $t('Misc.HorizontalDist') }}</div>
          </q-item>
          <q-item v-close-popup class="row no-wrap items-center" clickable @click="handleXY('distribution', 'y')">
            <q-icon :name="biDistributeVertical" class="q-pr-xs"></q-icon>
            <div>{{ $t('Misc.VerticalDist') }}</div>
          </q-item>
        </q-list>
      </q-popup-proxy>
    </q-btn>
    <q-btn :disable="!canUndo" :label="$t('Undo')" icon="mdi-undo-variant" v-bind="btnAttrs"
      @click="handleLast"></q-btn>
    <q-btn :disable="!canRedo" :label="$t('Redo')" icon="mdi-redo-variant" v-bind="btnAttrs"
      @click="handleNext"></q-btn>
  </q-btn-group>
</template>

<script setup>
import { i18n } from 'boot/i18n'
import {
  canRedo, canUndo, currentAction, exportAttrs, setCanRedo, setCanUndo, setCurrentAction, setCurveInfo
} from 'src/views/MapCore/MapGlobal/utils/KonvaEvent'
import {
  batchCreateLine, fillUndoList, handleAlign, handleDistribution, handleRedo, handleUndo
} from 'src/views/MapCore/MapGlobal/utils/MouseEvent'
import { computed, ref } from 'vue'
import { createWarnTips } from 'src/utils/utils'
import { biDistributeHorizontal, biDistributeVertical } from '@quasar/extras/bootstrap-icons'

const XMap = ref(new Map())
const YMap = ref(new Map())
const curveForm = ref({})
const XDisable = ref(true)
const YDisable = ref(true)
const btnAttrs = { padding: '.25rem .75rem', stack: true, class: 'text-grey-3' }
const batchLineForm = ref({ up: false, down: false, left: false, right: false })
const popupAttrs = {
  offset: [0, 3], anchor: 'bottom left', breakpoint: 0, self: 'top left', transitionHide: 'jump-up',
  transitionShow: 'jump-down'
}
const activeCls = computed(() => type => currentAction.value === type ? 'grey-9' : '')
const batchLineColumns = computed(() => {
  return [{
    label: i18n.t('Misc.Up'), field: 'up', disable: YDisable.value
  }, {
    label: i18n.t('Misc.Down'), field: 'down', disable: YDisable.value
  }, {
    label: i18n.t('Misc.Left'), field: 'left', disable: XDisable.value
  }, {
    label: i18n.t('Misc.Right'), field: 'right', disable: XDisable.value
  }]
})
const curveOptions = computed(() => {
  return [{
    label: `${i18n.t('Misc.Horizontal')}`, value: 180
  }, {
    label: `${i18n.t('Misc.Vertical')}`, value: 90
  }]
})
const curveOption = computed(() => {
  return {
    span: 24,
    column: [{
      label: `${i18n.t('MapCore.StartDirection')}`, field: 'startAngle', type: 'radio', value: 180,
      options: curveOptions.value
    }, {
      label: `${i18n.t('MapCore.EndDirection')}`, field: 'endAngle', type: 'radio', value: 180,
      options: curveOptions.value
    }, {
      label: `${i18n.t('MapCore.Bothway')}`, field: 'isDouble', type: 'switch',
      falseValue: '0', trueValue: '1', value: '0', class: 'custom-switch'
    }]
  }
})
const batchLineBeforeShow = () => {
  if (currentAction.value !== 'pointSelection') return
  const { batchSelected = [] } = exportAttrs()
  if (batchSelected.length < 2) return createWarnTips({ title: i18n.t('MapCore.OperationTip2') })
  if (!['Image'].includes(batchSelected[0].getClassName())) return
  for (const item of batchSelected) {
    const { x = 0, y = 0 } = item.position()
    if (XMap.value.has(y)) XMap.value.get(y).push(item) && (XDisable.value = false)
    else XMap.value.set(y, [item])
    if (YMap.value.has(x)) YMap.value.get(x).push(item) && (YDisable.value = false)
    else YMap.value.set(x, [item])
  }
  XMap.value.forEach((value, key) => value.length < 2 && XMap.value.delete(key))
  YMap.value.forEach((value, key) => value.length < 2 && YMap.value.delete(key))
  if (!XMap.value.size && !YMap.value.size) createWarnTips({ title: i18n.t('MapCore.OperationTip7') })
}
const batchLineHide = () => {
  XDisable.value = true
  YDisable.value = true
  XMap.value.clear()
  YMap.value.clear()
  batchLineForm.value = { up: false, down: false, left: false, right: false }
}
const handleXY = (type, dir) => {
  if (currentAction.value !== 'pointSelection') return createWarnTips({ title: i18n.t('MapCore.OperationTip9') })
  const { batchSelected = [], CANVAS } = exportAttrs()
  if (type === 'align') return handleAlign(CANVAS, batchSelected, dir)
  handleDistribution(CANVAS, batchSelected, dir)
}
const handleBatchLine = dir => {
  if (currentAction.value !== 'pointSelection') return createWarnTips({ title: i18n.t('MapCore.OperationTip9') })
  const Map = ['up', 'down'].includes(dir) ? YMap.value : XMap.value
  const lines = []
  const { CANVAS } = exportAttrs()
  Map.forEach(value => {
    const tempLines = batchCreateLine(CANVAS, value, dir)
    tempLines && lines.push(...tempLines)
  })
  if (!lines.length) return
  const { redoList, undoList } = exportAttrs()
  fillUndoList(undoList, redoList, lines, 'createLine')
  setCanUndo(undoList.length > 0)
  setCanRedo(redoList.length > 0)
}
const handleLast = () => {
  const { CANVAS, redoList = [], undoList = [] } = exportAttrs()
  handleUndo(CANVAS, undoList, redoList)
  setCanUndo(undoList.length > 0)
  setCanRedo(redoList.length > 0)
}
const handleNext = () => {
  const { CANVAS, redoList = [], undoList = [] } = exportAttrs()
  handleRedo(CANVAS, redoList, undoList)
  setCanUndo(undoList.length > 0)
  setCanRedo(redoList.length > 0)
}

const curvePopupHide = setCurveInfo(curveForm.value)
</script>